<?php

namespace App\Services;

use App\Models\OrderDetail;
use App\Models\Shop;
use App\Models\ShopGood;
use App\Models\ShopUser;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class ShopService
{

    /**
     * 添加店铺
     * @param $params
     * @return int
     */
    public static function addShop($params): int
    {
        $user_id = $params['user_id'];
        $avatar = $params['avatar'];
        $shop = Shop::query()->where("user_id",$user_id)->first();
        if (!$shop){
            $shop = new Shop;
            $shop->user_id = $user_id;
            $shop->avatar = $avatar;
            $shop->name = $params['nickname'];
        }else{
            if ($shop->state!=1){
                $shop->state = 0;
            }
        }
        $shop->fullname = $params['fullname'];
        $shop->phone = $params['phone'];
        $shop->id_card = $params['id_card'];
        $shop->id_card_image = $params['id_card_image'];
        $shop->student_card_image = $params['student_card_image'];
        $shop->save();
        $shop_id = $shop->id;
        $username = $params['phone'];
        $password = Hash::make($params['password']);
        self::saveShopUser($user_id, $shop_id, $username, $password, $avatar);
        return $shop_id;
    }

    /**
     * 设置店铺账号
     * @param $user_id
     * @param $shop_id
     * @param $username
     * @param null $password
     * @param null $avatar
     * @return bool
     */
    public static function saveShopUser($user_id, $shop_id, $username, $password = null, $avatar = null): bool
    {
        $shopUser = ShopUser::query()->where("user_id",$user_id)->first();
        if (!$shopUser){
            $shopUser = new ShopUser;
            $shopUser->user_id = $user_id;
            $shopUser->avatar = $avatar;
        }
        $shopUser->username = $username;
        $shopUser->shop_id = $shop_id;
        if ($password){
            $shopUser->password = $password;
        }
        $res = $shopUser->save();
        if ($res){
            Shop::whereId($shop_id)->update(['shop_user_id'=>$shopUser->id]);
            User::whereId($user_id)->update(['shop_id'=>$shop_id]);
        }
        return $res;
    }

    /**
     * 获取店铺的商品列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id): array
    {
        $user = User::whereId($user_id)->first();
        $shop_id = $user->shop_id;
        $cate = request()->input("cate",0);
        $state = request()->input("state",0);
        $page = request()->input("page",1);
        $pageSize = request()->input("pageSize",10);
        $list = ShopGood::query()->select(["shop_goods.*"])
            ->join("goods","goods.id","=","shop_goods.good_id")
            ->join("shops","shops.id","=","shop_goods.shop_id")
            ->with(['goods'=>function($query) {
                $query->select(["id","name","category_id","image","images","cost_price","unit","stock"]);
            },'shop'])
            ->withCount('visit')
            ->withCount('sales')
            ->where("shop_goods.state",$state)
            ->where("shop_goods.shop_id",$shop_id)
            ->where("shops.status",0)
            ->where("shops.state",1)
            ->where("goods.state",0)
            ->where("goods.status",$state)
            ->when($cate,function ($query) use ($shop_id){
                $query->where("goods.cate","second")->where("stock",1)->where(function ($query) use ($shop_id){
                    $query->whereNotIn("shop_goods.id",OrderDetail::query()->where("sg_shop_id",$shop_id)->pluck("sg_id"));
                });
            })
            ->when(!$cate,function ($query){
                $cateList = ["real","virtual"];
                $query->whereIn("goods.cate",$cateList);
            })
            ->orderByDesc("id")
            ->paginate($pageSize);
        $items = collect($list->items())->toArray();
        foreach ($items as $key=>$item){
            $goods = $item['goods'];
            $items[$key]['good_name'] = $goods['name'];
            if ($goods['image']){
                $items[$key]['good_image'] = cdn_url($goods['image']);
            }else{
                if ($goods['images']){
                    $items[$key]['good_image'] = cdn_url($goods['images'][0]);
                }else{
                    $items[$key]['good_image'] = "";
                }
            }
            $items[$key]['category_id'] = $goods['category_id'];
            $items[$key]['category_name'] = $goods['category']['name'];
            $items[$key]['unit'] = $goods['unit'];
            $items[$key]['stock'] = $goods['stock'];
            unset($items[$key]['goods']);
            unset($items[$key]['sku_prices']);
            if ($items[$key]['shop']['avatar']){
                $items[$key]['shop']['avatar'] = cdn_url($item['shop']['avatar']);
            }else{
                $items[$key]['shop']['avatar'] = letter_avatar($item['shop']['name'], 1);
            }
            $items[$key]['city_name'] = $user->area->name??"";
            $items[$key]['school_name'] = $user->school->name??"";
        }
        $data['items'] = $items;
        $data['page'] = $page;
        $data['pageSize'] = $pageSize;
        $data['total'] = $list->total();
        $data['lastPage'] = $list->lastPage();
        return $data;
    }
}
